var stepToolFrom = function () {
    console.log('stepToolFrom')
};
var stepToolEdit = function () {
    console.log('stepToolEdit')
};
var stepToolSetting = function () {
    console.log('stepToolSetting')
};
var stepToolTo = function (event) {
    let step = $(event);
    let id = step.attr('id');
    let options = step.designerstep('options');
    let common = options.jsPlumbCommon;
    // jsPlumb.addEndpoint(editor, {anchors: ['Center']}, common)
    // console.log(jsPlumb.getEndpoints())
    console.log(id)
    console.log(jsPlumb.getEndpoint(id))
};
jsPlumb.ready(function () {
    jsPlumb.setContainer('diagramContainer');

});


/*designer*/
(function ($) {
    $.extend({
        /*dev 本地开发环境,加载json文件作为api返回值 */
        designer: {
            baseUrl: './resource',
            get: function (url, param, callback) {
                let firstChar = url.substr(0, 1);
                url = this.baseUrl + ('/' === firstChar ? url : '/' + url);
                /*开发环境加载本地json,模拟api调用*/
                $.get(url, callback)
            },
            post: function (url, param, callback) {

            },
            put: function (url, param, callback) {

            },
            delete: function (url, param, callback) {

            },
        }
    });
    $.extend({
        /*uuid函数 返回时间戳+ 随机数转36进制*/
        uuid: function () {
            return Date.now() + '-' + Math.random().toString(36).substr(2);
        }
    })

})(jQuery);

/*designermenu 设计器-菜单 */
(function ($) {
    $.fn.designermenu = function (method, param) {
        if (typeof method == "string") {
            return $.fn.designermenu.methods[method](this, param);
        }
        param = method || {};
        return this.each(function () {
            //全局参数
            var data = $(this).data("designermenu");
            if (data) {
                //合并属性
                $.extend(data.options, param);
            } else {
                //初始化属性
                let options = $.extend({}, $.fn.designermenu.defaults, $.fn.designermenu.parseOptions(this), param, {});
                $(this).data("designermenu", {options: options});
            }
            /*构建dom结构和渲染*/
            let options = $(this).data("designermenu").options;
            let menu = $(this).draggable({
                proxy: 'clone',
                revert: true,
                onEndDrag: function (e) {
                    let proxy = $(this).draggable('proxy');
                    let offset = proxy.offset();
                    let left = Math.round(offset.left);
                    let top = Math.round(offset.top);
                    if (left >= 180) {
                        let stepParam = {
                            left: left,
                            top: top,
                            stepTitle: options.menuTitle,
                            stepType: options.stepType
                        };
                        $('<div></div>').appendTo('#designerDesign').designerstep(stepParam);
                    }
                },
            });
            menu.append('<div class="designer-menu-icon ' + options.iconCls + '"></div><div class="designer-menu-title">' + options.menuTitle + '</div>');
        });
    };
    $.fn.designermenu.parseOptions = function (selector) {
        let dom_data_options = $.parser.parseOptions(selector);
        var options = $.extend({}, dom_data_options, {iconCls: (dom_data_options.iconCls ? dom_data_options.iconCls : 'designer-menu-' + dom_data_options.stepType)});
        return options;
    };
    /*menuTitle=标题,stepType=步骤类型,classify=分类,iconCls=图标,sort=排序,enable=启用,designerDesign=设计窗口id*/
    $.fn.designermenu.defaults = {
        menuTitle: null,
        stepType: null,
        classify: null,
        iconCls: null,
        sort: null,
        enable: 1,
    };
    $.fn.designermenu.methods = {
        options: function (event) {
            return event.data("designermenu").options;
        }
    };


})(jQuery);

/*designerstep 设计器-步骤 */
(function ($) {
    $.fn.designerstep = function (method, param) {
        if (typeof method == "string") {
            return $.fn.designerstep.methods[method](this, param);
        }
        param = method || {};
        return this.each(function () {
            //全局参数
            var data = $(this).data("designerstep");
            if (data) {
                //合并属性
                $.extend(data.options, param);
            } else {
                //初始化属性
                let stepType = param.stepType;
                let options = $.extend({}, $.fn.designerstep.defaults, $.fn.designerstep.parseOptions(this), param);
                options = $.extend({}, options, {
                    iconCls: (options.iconCls && options.iconCls !== '' ? options.iconCls : 'designer-step-' + stepType),
                    stepTitle: ((options.stepTitle && options.stepTitle !== '') ? options.stepTitle : options.stepName)
                });
                if (options.stepId && options.stepId !== '') {
                    options.id = options.stepId;
                }
                $(this).data("designerstep", {options: options});
            }
            /*构建dom结构和渲染*/
            let options = $(this).data('designerstep').options;
            let offset = {left: options.left, top: options.top};
            $(this).attr('id', options.id).addClass("step-draggable").offset(offset);
            // let stepDraggable = $(this).addClass("step-draggable").offset(offset).draggable(options);
            let designStep = $('<div class="designer-step"></div>').appendTo($(this));
            let stepIcon = $('<div class="designer-step-icon ' + options.iconCls + '"></div>').appendTo(designStep);
            let stepTitle = $('<div class="designer-step-title">' + options.stepTitle + '</div>').appendTo(designStep);
            let stepTool = $('<a href="#" class="designer-step-tool"></a>').appendTo(stepIcon).tooltip({
                content: '<div class="designer-step-opt" >' +
                    '        <div class="designer-step-opt-title">' + options.stepTitle + '</div>' +
                    '        <div class="designer-step-opt-main">' +
                    '               <span class="designer-step-opt-btn"><span class="designer-step-opt-btn-icon designer-step-opt-from" onclick="stepToolFrom()"></span></span>' +
                    '               <span class="designer-step-opt-btn"><span class="designer-step-opt-btn-icon designer-step-opt-edit" onclick="stepToolEdit()"></span></span>' +
                    '               <span class="designer-step-opt-btn"><span class="designer-step-opt-btn-icon designer-step-opt-setting" onclick="stepToolSetting()"></span></span>' +
                    '               <span class="designer-step-opt-btn"><span class="designer-step-opt-btn-icon designer-step-opt-to" onclick="stepToolTo(\'#' + options.id + '\')"></span></span>' +
                    '        </div>' +
                    '      </div>',
                position: 'bottom', deltaX: 18, deltaY: 36,
                showDelay: 500, hideDelay: 400, showEvent: 'mouseenter',
            });
            //拖动设置 stepDraggable
            jsPlumbInit(this);
            //绑定事件
            let step = $(this);

            let eventData = {event:step,param:{stepType:options.stepType,stepId: options.stepId, title: options.stepTitle}};
            stepIcon.bind('mouseover', eventData, function (event) {
                let param = event.data.param;
                let stepId = param.stepId;
                let tool = $(this).find('.designer-step-tool');
                tool.tooltip('show');
                tool.tooltip('tip').hover(function () {
                    tool.tooltip('show')
                }, function () {
                    tool.tooltip('hide')
                })

            }).bind('mouseleave', eventData, function (event) {
                let param = event.data.param;
                let stepId = param.stepId;
                let tool = $(this).find('.designer-step-tool');
                tool.delay(1000).tooltip('hide');
            }).bind('dblclick', eventData, function (event) {
                let step= event.data.event;
                let param = event.data.param;
                step.designerstep('editor',param);
            });

        });

    };
    $.fn.designerstep.parseOptions = function (selector) {
        let options = $.extend({}, $.parser.parseOptions(selector));
        options = $.extend(options, {id: (options.stepId && options.stepId !== '' ? options.stepId : "step_" + Date.now() + Math.random().toString(36).substr(2))});
        if (options.stepType && !options.iconCls) {
            options.iconCls = 'designer-step-' + options.stepType
        }
        return options;
    };
    /*designerstep 设计器-步骤 内置属性, 对应表单*/
    $.fn.designerstep.defaults = {
        id:'',
        stepId:'',
        data: {},
        jsPlumbCommon: {
            grid: [10, 10], //拖动属性 网格对齐= 每次移动固定的尺寸
            maxConnections: -1,//端点最多拉出线条数 n , -1不限制
            // Detachable:false, //连接线是否可以使用鼠标默认分离
            // connectionsDetachable:false,//拖动后让连接断开
            isSource: true,//拖动发生时,自动变更线条
            isTarget: true,//拖动发生时,自动变更线条
            // labelStyle:[],
            RenderMode: "svg",//渲染模式
            // anchor: ['Center'], //默认连接点位置
            /*anchor.Perimeter图形  Circle 圆,Ellipse 椭圆,Triangle 三角, Diamond 菱形, Rectangle矩形, Square 方形*/
            // anchor: ['Perimeter ',{faces:["top","right","Bottom","left"]}], //默认连接点位置  //Continuous
            /*anchor.Continuous根据节点位置，自动调整位置的锚点  Circle 圆,Ellipse 椭圆,Triangle 三角, Diamond 菱形, Rectangle矩形, Square 方形*/
            anchor: ['Continuous', {faces: ["top", "right", "Bottom", "left"]}], //默认连接点位置  //Continuous
            // anchors: ['Center','Center'], //多个锚点
            containment: '#designerDesign', //containment可拖动区域 parent selector,需要jqueryUI支持

            paintStyle: {stroke: '#3D6380', strokeWidth: 1},//颜色
            hoverPaintStyle: {strokeWidth: 2},//鼠标悬浮颜色

            endpoint: ["Dot", {radius: 5}], //endpoint端点:  Dot 圆点,Rectangle 矩形,Image 图像,Blank 空白
            // endpoints:[], 多个锚点
            endpointStyle: {fill: 'lightgray'},
            /*Connectors*/
            connector: ['Flowchart'],//connector 连接线     Bezier 贝塞尔曲线,Straight 直线,Flowchart 90度转角线,StateMachine 状态机

            // Scope:"",//范围
            overlays: [
                // ["Arrow",{location:0.1}], //箭头
                ["PlainArrow", {location: 0.6}],//三角
                // ["Label",{location:0.4,label:"label"}],//标签
                // ["Diamond",{location:0.7}],//菱形
                /*["Custom",{create:function (component) {},location: 0.9,id:""}],//自定义 */
            ], // 叠加层
        },
        onClick:function(){},
        onDblclick:function (event,param) {
            /*let editorOpts = $.extend({},{data:event.data});
            let editor = $('#editorChoosecol');
            if (!editor.length) {
                editor = $('<div id="editorChoosecol"></div>').appendTo('body');
                editor.editorChoosecol(editorOpts);

            }else{
                editor.editorChoosecol('open',editorOpts);
            }*/
        }
    };
    /*designerstep 设计器-步骤 内置方法*/
    $.fn.designerstep.methods = {
        options: function (event) {
            return event.data("designerstep").options;
        }
        , getData: function (event) {
            // let options = event.data("designerstep").options;
            // return options.data;
        }, link: function (event) {
            // let options = jq.step('options');
            // let fromStepId = options.fromStepId;
            // let stepId = options.stepId;
            // let toStepId = options.toStepId;
            // if (fromStepId) {
            //     linkStep(fromStepId, stepId);
            // }
            // if (toStepId) {
            //     linkStep(stepId, toStepId);
            // }
        }, fromStep: function (jq, from, to) {

        }, toStep: function (jq, from, to) {

        },
        editor:function (event,param) {
            let stepType = param.stepType;
            if('choosecol'===stepType){
                let editor = $('#editorChoosecol');
                if (!editor.length) {
                    editor = $('<div id="editorChoosecol"></div>').appendTo('body');
                    editor.editorChoosecol(param);
                }else{
                    editor.editorChoosecol('open',param);
                }
            }else if('jsonparse'===stepType){
                let editor = $('#editorJsonparse');
                if (!editor.length) {
                    editor = $('<div id="editorJsonparse"></div>').appendTo('body');
                    editor.editorJsonparse(param);
                }else{
                    editor.editorJsonparse('open',param);
                }
            }else{
                $.messager.alert('系统消息','组件尚未开发完成.'+stepType,'warning')
            }

        }
    };

    function jsPlumbInit(event) {
        // let that = $(event).find('.designer-step-icon');
        let that = $(event);
        let common = $(event).designerstep('options').jsPlumbCommon;
        //拖动元素
        jsPlumb.draggable($(event), common);
        //锚点设置

        // console.log(that)
        jsPlumb.addEndpoint(that, {anchors: ['Center']}, common)
        // jsPlumb.addEndpoint(that, {anchors: ['Left']}, common)
        // jsPlumb.addEndpoint(that, {anchors: ['Bottom']}, common)
        // jsPlumb.addEndpoint(that, {anchors: ['Top']}, common)

    };


})(jQuery);

/*designerstep-line 设计器-步骤-连接线 */
(function ($) {
    $.fn.designerline = function (method, param) {
        if (typeof method == "string") {
            return $.fn.designerstep.methods[method](this, param);
        }
        param = method || {};
        return this.each(function () {
            //全局参数
            var data = $(this).data("designerline");
            if (data) {
                //合并属性
                $.extend(data.options, param);
            } else {
                //初始化属性
                let stepType = param.stepType;
                let options = $.extend({}, $.fn.designerstep.defaults, $.fn.designerstep.parseOptions(this), param);
                options = $.extend({}, options, {
                    iconCls: (options.iconCls && options.iconCls !== '' ? options.iconCls : 'designer-step-' + stepType),
                    stepTitle: ((options.stepTitle && options.stepTitle !== '') ? options.stepTitle : options.stepName)
                });
                if (options.stepId && options.stepId !== '') {
                    options.id = options.stepId;
                }
                $(this).data("designerstep", {options: options});
            }
            /*构建dom结构和渲染*/
        });
    };
    $.fn.designerline.defaults = {
        maxConnections: 1,//端点最多拉出线条数 n , -1不限制
        grid: [10, 10], //网格对齐= 每次移动固定的尺寸
        containment: '#designerDesign', //containment可拖动区域 parent selector,需要jqueryUI支持
        paintStyle: {outlineStroke: 'blue', stroke: 'lightgray', strokeWidth: 1},//颜色全局
        hoverPaintStyle: {outlineStroke: 'lightblue', strokeWidth: 2},//鼠标悬浮颜色全局
        //anchors锚点 Static 静态 固定位置的锚点;Dynamic jsPlumb自动选择合适的锚点，动态锚点;Perimeter 边缘锚点，会根据节点形状去改变位置;Continuous 根据节点位置，自动调整位置的锚点
        anchors: ['Static'
            // 'Right', 'Left', 'Bottom', 'Top',
            // 'TopCenter', 'TopRight', 'TopLeft',  'RightMiddle',
            // 'BottomCenter', 'BottomRight', 'BottomLeft',  'LeftMiddle'
        ],
        isSource: true,//拖动发生时,自动变更线条
        isTarget: true,//拖动发生时,自动变更线条
        endpoint: ["Dot", {radius: 5}], //endpoint端点:  Dot 圆点,Rectangle 矩形,Image 图像,Blank 空白
        endpointStyle: {fill: 'lightgray', outlineStroke: 'darkgray', outlineWidth: 1},
        connector: ['Flowchart'],//connector 连接线     Bezier 贝塞尔曲线,Straight 直线,Flowchart 90度转角线,StateMachine 状态机
        connectorStyle: {outlineStroke: 'green', strokeWidth: 1},
        connectorHoverStyle: {strokeWidth: 2},
    };
    $.fn.designerline.methods = {
        lineTo: function (event, target) {
            console.log(this)
            console.log(event)
            console.log(target)
        },
        lineFrom: function (event, source) {
            console.log(this)
            console.log(event)
            console.log(source)
        },
    }
})(jQuery);

/* editorChoosecol */
(function ($) {
    $.fn.editorChoosecol = function (method, param) {
        if (typeof method == "string") {
            return $.fn.editorChoosecol.methods[method](this, param);
        }
        param = method || {};
        //全局参数
        var data = $(this).data("editorChoosecol");
        if (data) {
            //合并属性
            $.extend(data.options, param);
        } else {
            //初始化属性
            let options = $.extend({}, $.fn.editorChoosecol.defaults, param);
            $(this).data("editorChoosecol",{options:options});
            // let dg = $('<table id="choisecolSettings"></table>').appendTo(this).datagrid(options.datagrid);
            $(this).dialog(options.dialog);
            $('#editorChoosecolDatagrid').datagrid(options.datagrid);
            // $(this).editorChoosecol('loadData');
        }
    };
    $.fn.editorChoosecol.defaults = {
        url:{getStepEditor:'/editor/choosecol.json',save:'/editor/save/choosecol'},
        stepId:'',
        data:{},
        dialog: {
            id: 'editorChoosecol',
            title: '字段选择',
            iconCls: 'designer-menu-choosecol',
            width: 760,
            height: 480,
            left:100,
            top:5,
            // fit:true,
            // footer:'#stepFoot',
            collapsible: false,//折叠按钮
            minimizable: false,
            maximizable: false,
            draggable: false,//拖拽
            resizable:false,//改变窗口大小
            shadow:true,//如果设置为true，在窗体显示的时候显示阴影。
            inline:false,
            modal:true,
            border:true,//true，false，'thin'，'thick'
            constrain:false, //定义是否限制窗体的位置。
            // openAnimation: 'show', //动画，'slide','fade','show'。
            content:'<table id="editorChoosecolDatagrid"></table>',
            buttons:[{iconCls:'icon-ok',text:'确定',onClick:function () {$('#editorChoosecol').editorChoosecol('save')}},{text:'取消',onClick:function () {$('#editorChoosecol').editorChoosecol('close')}}], //selector | [{linkdbutton-options}]
            onOpen:function (event){
                $(this).editorChoosecol('loadData');
            }
        },
        datagrid: {
            fit:true,
            rownumbers: true,
            columns: [[
                {field: 'colName', title: '字段名称', width: 100, editor: 'text'},
                {field: 'colAlias', title: '改名成', width: 100, editor: 'text'},
                {
                    field: 'colType',
                    title: '类型',
                    width: 80,
                    editor: {
                        type: "combobox",
                        options: {
                            panelHeight: 150,
                            data: [{text: "String", value: 'String'}, {
                                text: "Integer",
                                value: 'Integer'
                            }, {text: "Number", value: 'Number'}, {text: "Date", value: 'Date'}, {
                                text: "Timestamp",
                                value: 'Timestamp'
                            }]
                        }
                    }
                },
                {field: 'colLength', title: '长度', width: 56, editor: 'text'},
                {field: 'cc', title: '精度', width: 56, editor: 'text'},
                {field: 'dateFormat', title: 'Date格式', width: 100, editor: 'text'},
                {field: 'notNull', title: 'NotNull', width: 56, editor: 'checkbox'},
            ]],
            onDblClickCell: function (index, field, value) {
                let options = $(this).datagrid('options');
                let editing = options.editing;
                if (editing || editing === 0) {
                    $(this).datagrid('endEdit', editing);
                }
                options.editing = index;
                $(this).datagrid('beginEdit', index)
                var ed = $(this).datagrid('getEditor', {index: index, field: field});
                $(ed.target).focus();
            },},
    };
    $.fn.editorChoosecol.methods = {
        options: function (event) {return event.data("editorChoosecol").options;},
        open:function (event,param) {
            event.dialog('open');
            let options = event.editorChoosecol('options');
            options= $.extend({},options,{data:{},stepId:''},param);
            event.data("editorChoosecol",{options:options});
            event.dialog('open');
        },
        close:function (event) { event.dialog('close')},
        getData:function (event) { return event.editorChoosecol('options').data;},
        loadData:function (event) {
            let options = event.editorChoosecol('options');
            if(options.stepId && options.stepId!==''){
                $.designer.get(options.url.getStepEditor,{stepType:'choosecol',stepId:options.stepId},function (res) {
                    if(res.success){
                        options=$.extend({},options,{data:res.result});
                        event.data('editorChoosecol',{options:options});
                        $('#editorChoosecolDatagrid').datagrid('loadData',options.data.settings);
                        // 初始化表单
                    }else{
                        $.messager.alert('系统错误', res.message || '系统发生错误!', 'warning')
                    }
                });
            }

        },
        save:function (event) {
            let options = event.editorChoosecol('options');
            let url = options.url.save;
            let data = options.data;

            $.messager.show({width:600,height:260,title:'保存提交',msg:'<p>url:'+url+'</p><p>data:'+JSON.stringify(data)+'</p>',timeout:2000})
        }
    };
})(jQuery);

/* editorJsonparse */
(function ($) {
$.fn.editorJsonparse=function (method, param) {
    if (typeof method == "string") {
        return $.fn.editorJsonparse.methods[method](this, param);
    }
    param = method || {};
    //全局参数
    var data = $(this).data("editorJsonparse");
    if (data) {
        //合并属性
        $.extend(data.options, param);
    } else {
        //初始化属性
        let options = $.extend({}, $.fn.editorJsonparse.defaults, param);
        var editor = $(this);
        $(this).addClass('designer-editor').data("editorJsonparse",{options:options});
        $(this).dialog(options.dialog);
        let tabs = $('<div id="editorJsonparseTabs"><div title="json结构" class="editor-jsonparse-setting"></div><div title="输出字段" class=""></div></div>').appendTo($(this).dialog('body')).tabs(options.tabs);
        let setting = $('.editor-jsonparse-setting').append('<div class="west"><div class="northwest"></div><div class="southwest"></div></div><div class="east"><ul id="editorJsonParseTree"></ul></div>');
        $('<input id="editorJsonParseWrite" style="width: 100%;height:100%">').appendTo(setting.find('.southwest')).textbox({multiline:true,readonly:true});
        let btn = $('<a href="#">解析模板</a>').appendTo( setting.find('.northwest'))
            .linkbutton({iconCls:'icon-reload',onClick:function () {
                $('<div id="editorJsonparseInput"></div>').appendTo(editor).dialog({
                    title:'请输入JSON模板',width:480,height:240,left:240,top:90,
                    content:'<input class="easyui-textbox" data-options="prompt:\'请输入json模板\',multiline:true," style="width: 100%;height:100%">',
                    buttons:[{iconCls:'icon-ok',text:'确认',onClick:function () {
                            let text = $('#editorJsonparseInput').dialog('body').find('input').textbox('getText');
                            let json;
                            try {
                                json = JSON.parse(text);
                            } catch (e) {
                                $.messager.alert("系统错误","输入文本不是标准JSON格式!","error")
                            }
                            if(json){
                                let res = templateCreate(json);
                                let treeNode = res.node;
                                let templateJson = res.defVal;
                                editor.editorJsonparse('writeTemplate',templateJson);
                                editor.editorJsonparse('buildTree',treeNode);
                                $('#editorJsonparseInput').dialog('destroy');
                            }
                        }
                    }],
                    onClose:function () {
                        $(this).dialog('destroy');
                    }
                });
            }});




    }
};
    $.fn.editorJsonparse.defaults={
        url:{getStepEditor:'/editor/jsonparse.json',save:'/editor/save/jsonparse'},
        stepId:'',
        data:{},
        dialog: {
            id: 'editorJsonparse',
            title: 'JSON解析',
            iconCls: 'designer-menu-jsonparse',
            width: 980,height: 620,left:30,top:1,
            // fit:true,
            // footer:'#stepFoot',
            collapsible: false,//折叠按钮
            minimizable: false,
            maximizable: false,
            draggable: false,//拖拽
            resizable:false,//改变窗口大小
            shadow:true,//如果设置为true，在窗体显示的时候显示阴影。
            inline:false,
            modal:true,
            border:true,//true，false，'thin'，'thick'
            constrain:false, //定义是否限制窗体的位置。
            // openAnimation: 'show', //动画，'slide','fade','show'。
            buttons:[{iconCls:'icon-ok',text:'确定',onClick:function () {$('#editorJsonparse').editorJsonparse('save')}},{text:'取消',onClick:function () {$('#editorJsonparse').editorJsonparse('close')}
            }],
            onOpen:function (){
                var text = '{"LIST":[{"CEE_MATERIAL":{"MAT_CODE":"1002331554","MAT_NAME":"箱体喷涂","MAT_MODEL":"测试修改","MAT_SPECIFICATOIN":"","MAT_SURFACE_DEAL":"","MAT_DETAIL":"","MAT_STANDARD":"","MAT_SUPPLY_STARD":"","MAT_CERTIFICATE":"厚度由80um抬高至120um","MAT_MEASUREMENT":"gm2","MAT_MEASUREMENT_MEA_UNIT_DESC":"GM2， 克/平方米","MAT_TYPE":"Z006","MAT_TYPE_TYPE_NAME":"Z006_虚拟物料","MAT_FEATURE_1":"","MAT_FEATURE_2":"","MAT_FEATURE_3":"","MAT_FEATURE_4":"","MAT_FEATURE_5":"","MAT_FEATURE_6":"","MAT_FEATURE_7":"","MAT_FEATURE_8":"","MAT_FEATURE_9":"","MAT_FEATURE_10":"","MAT_DESC":"箱体喷涂;测试修改;厚度由80um抬高至120um","MAT_S_DESC":"箱体喷涂;测试修改","MAT_CATEGORY3":"E2702020","MAT_CATEGORY1":"E27","MAT_CATEGORY2":"E2702","CATEGORY_PATH_CODE":"CEE_MATERIAL|E27|E2702|E2702020","MAT_CATEGORY3_NAME":"外委服务","MAT_CATEGORY1_NAME":"服务和解决方案","MAT_CATEGORY2_NAME":"工程及生产服务","CATEGORY_PATH_NAME":"物料主数据模型|服务和解决方案|工程及生产服务|外委服务","DATAID":"","DATASTATUS":"0","STOPREASON":"","CREATEDATE":"2025-08-27 10:10:13","CREATEUSER":"14016349","CREATEDEPT":"14000330","VALIDDATE":"2025-08-27 11:33:58","MODIFYUSER":"zhushuju","CHILDMODELS_1":[{"CEE_MATERIAL_01":{"DATAID":"c66a5626d9db4e6fa065aef09132418d","USE_MODEL_CODE":"CEE_MATERIAL","HISTORICAL_CODE":"704306006","SYSTEM_NAME":"XJ01ERP001","CREATEDEPT_NAME":"生产部","CREATEDEPT":"EFFD7B192B534183AFC9F05DF2F0E180","CREATEUSER_NAME":"罗明超","COMPANY_COMPANY_NAME":"许继","CREATEDEPT_CODE":"14000330","SYNC_STATUS":"0","CREATEUSER":"14016349","VERSIONSTATUS":"1","USE_MODEL_NAME":"物料主数据模型","ID":"7b66098199ce441b8ec0acb84fe724bc","SECRETLEVEL":"1","CATEGORY_CODE":"E2702020","CREATEDATE":"2025-08-27 10:10:13","MODIFYUSER":"14016349","USE_DATA_ID":"c66a5626d9db4e6fa065aef09132418d","MODIFYTIME":"2025-08-27 11:33:58","MAXVERSION":"1","MAT_CODE":"1002331554","CREATEUSER_CODE":"14016349","COMPANY":"1002","VERSION":"1","VALIDDATE":"2025-08-27 11:33:58","DATAORIGIN":"CIDP"}}]},"CIDP_TASK_UUID":"f1d0a3123cfa47c6acf307f5d83e0680"}],"tableName":"CEE_MATERIAL"}';
                let res = templateCreate(JSON.parse(text));
                let treeNode = res.node;
                let templateJson = res.defVal;
                let editor = $(this);
                $(function () {
                    editor.editorJsonparse('writeTemplate',templateJson);
                    editor.editorJsonparse('buildTree',treeNode);
                })

            }
        },
        tabs:{plain:true,fit:true,border:false},
        tree:{
            data:[]
        },
    };
    $.fn.editorJsonparse.methods={
        options: function (event) {return event.data("editorJsonparse").options;},
        open:function (event,param) {

            let options = event.editorJsonparse('options');
            options= $.extend({},options,{data:{},stepId:''},param);
            event.data("editorJsonparse",{options:options});
            event.dialog('open');

        },
        close:function (event) { event.dialog('close')},
        getData:function (event) { return event.editorJsonparse('options').data;},
        loadData:function (event) {
            let options = event.editorJsonparse('options');
            let stepId =options.stepId;
            if(stepId && stepId!==''){
                $.designer.get(options.url.getStepEditor,{stepType:'jsonparse',stepId:options.stepId},function (res) {
                    if(res.success){
                        //渲染数据
                        options=$.extend({},options,{data:res.result});
                        event.data('editorJsonparse',{options:options});
                        event.dialog('body').text(JSON.stringify(res.result))
                    }else{
                        $.messager.alert('系统错误', res.message || '系统发生错误!', 'warning')
                    }
                });
            }
        },
        save:function (event) {
            let options = event.editorJsonparse('options');
            let url = options.url.save;
            let data = options.data;

            $.messager.show({width:600,height:260,title:'保存提交',msg:'<p>url:'+url+'</p><p>data:'+JSON.stringify(data)+'</p>',timeout:2000})
        },
        writeTemplate:function (event,templateJson) {
            let options=event.editorJsonparse('options');
            event.data('editorJsonparse',{options:$.extend({},options,{data:{templateJson:templateJson}})});
            let text = JSON.stringify(templateJson,null,2);
            $('#editorJsonParseWrite').textbox('setText',text);
        },
        buildTree:function (event,treeNode) {
            let options=event.editorJsonparse('options');
            event.data('editorJsonparse',{options:$.extend({},options,{data:{treeNode:treeNode}})});
            let data =[];
            if(treeNode instanceof Object){
                treeNode.text='ROOT';
                data.push(treeNode)
            }else{
                data=treeNode;
            }
            console.log(data);
            $('#editorJsonParseTree').tree({data:data,lines:true,checkbox:true,dnd:true});
        }

    };
/*
id：节点ID，对加载远程数据很重要。
text：显示节点文本。
state：节点状态，'open' 或 'closed'，默认：'open'。如果为'closed'的时候，将不自动展开该节点。
checked：表示该节点是否被选中。
attributes: 被添加到节点的自定义属性。
children: 一个节点数组声明了若干节点。
*/


    function templateCreate(source) {
        if(typeof source ==='string'){
            return {node:{type:'String'},defVal:''};
        }else if(typeof source ==='number'){
            return {node:{type:'Number'},defVal:0};
        }else if(typeof source ==='boolean'){
            return {node:{type:'Boolean'},defVal:true};
        }else if(typeof source ==='undefined'){
            console.log('undefined-->')
            console.log(source)
            return {node:{type:'undefined'},defVal:null};
        }else{
            if(source instanceof Array){
                console.log('Array-->')
                let tree={type:'Array',children:[]};
                let defVal=[];
                $.each(source,(i,e)=>{
                    let res = templateCreate(e);
                    tree.children.push(res.node);
                    defVal.push(res.defVal);
                });
                return {node:tree,defVal: defVal};
            }else if(source instanceof Object){
                let tree={type:'Object',text:'',children:[]};
                let defVal={};
                $.each(source,(k,v)=>{
                    let res = templateCreate(v);
                    let node = $.extend({},res.node,{text:k});
                    tree.children.push(node);
                    defVal[k]=res.defVal;
                });
                return {node:tree,defVal: defVal};
            }else{
                $.messager.alert('系统消息','无法识别的数据类型!','warning');
            }
        }
    }
})(jQuery);


